<template>
	<div>
		<div style="display: inline-block;">
			<div style="display: inline-block;margin: 5px;">
				<span>类型：</span>
				<el-select v-model="queryForm.type" style="width:150px;margin-left: 10px;">
					<el-option v-for="item in statesnum" :key="item.value" :label="item.label" :value="item.value">
					</el-option>
				</el-select>&nbsp;&nbsp;
			</div>
			<el-button style='margin-left:15px;' size="mini" type="primary" icon="document" @click="homeSelect">查询
			</el-button>
			<el-button style='margin-left:15px;' size="mini" type="primary" icon="document" @click="cleans">重置
			</el-button>
			<el-button style='margin-left:15px;' size="mini" type="primary" icon="document" @click="addBtn()">添加
			</el-button>
		</div>
		<el-table v-loading="tableDataLoading" :data="homeData.list">
			<el-table-column fixed prop="id" label="编号" width="80" />
			<el-table-column prop="riderName" label="司机姓名" width="100" />
			<el-table-column prop="area" label="路线区域" width="200" />
			<el-table-column prop="startPointLat" label="路线起点" width="250">
				<template slot-scope="scope">
					<div>{{getAddressLatLng(scope.row.startPointLat,scope.row.startPointLng)}}</div>
				</template>
			</el-table-column>
			<el-table-column prop="endPointLat" label="路线终点" width="250">
				<template slot-scope="scope">
					<div>{{getAddressLatLng(scope.row.endPointLat,scope.row.endPointLng)}}</div>
				</template>
			</el-table-column>
			<el-table-column prop="wayPoints" label="途径点" max-width="300">
				<template slot-scope="scope">
					<div>{{ getWayPointsString(scope.row.wayPoints) }}</div>
				</template>
			</el-table-column>
			<el-table-column label="操作" width="200" fixed="right">
				<template slot-scope="scope">
					<el-button size="mini" type="primary" style="margin: 5px;"
						@click="looking(scope.row)">查看</el-button>
					<el-button style='margin:5px;' size="mini" type="primary" @click="compile(scope.row)">删除
					</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div style="text-align: center;margin-top: 10px;">
			<el-pagination @size-change="handleSizeChange1" @current-change="handleCurrentChange1"
				:page-sizes="[10, 20, 30, 40]" :page-size="size" :current-page="page"
				layout="total,sizes, prev, pager, next,jumper" :total="homeData.totalCount">
			</el-pagination>
		</div>



		<!-- 添加/修改 任务 -->
		<el-dialog :title="titles" :visible.sync="dialogFormVisibleRw" center width="50%">

			<div style="margin-bottom: 10px;display: flex;">
				<span style="width: 200px;display: inline-block;text-align: right;">司机：</span>
				<el-select v-model="tableData.riderId" style="width:45%;" filterable @change="SelectDriver">
					<el-option v-for="item in driverList" :key="item.userId" :label="item.userName"
						:value="item.userId">
					</el-option>
				</el-select>
			</div>
			<div style="margin-bottom: 10px;display: flex;">
				<span style="width: 200px;display: inline-block;text-align: right;">区域：</span>
				<el-input v-model="tableData.area" style="width:45%;" placeholder="区域" @change="areaSeclect"></el-input>
			</div>

			<div style="margin-bottom: 10px;display: flex;">
				<span style="width: 200px;display: inline-block;text-align: right;">发车点：</span>
				<el-select v-model="startPoint" style="width:45%;" @change="SelectStartPoint">
					<el-option v-for="item in areaList" filterable :key="item.id" :label="item.name" :value="item.id">
					</el-option>
				</el-select>
			</div>
			<div style="margin-bottom: 10px;display: flex;">
				<span style="width: 200px;display: inline-block;text-align: right;">停车点：</span>
				<el-select v-model="endPoint" style="width:45%;" @change="SelectEndPoint">
					<el-option v-for="item in areaList" filterable :key="item.id" :label="item.name" :value="item.id">
					</el-option>
				</el-select>
			</div>


			<div style="margin-bottom: 10px;display: flex;">
				<span style="width: 200px;display: inline-block;text-align: right;">途径点：</span>
				<div style="width: 45%;max-height: 15vh;overflow: hidden;overflow-y: auto;">
					<div style="width: 100%;margin-bottom: 10px; display: flex;align-items: center;justify-content: space-between;"
						v-for="(item,index) in PointList" :key="index">
						<div
							style="width: 20px;height: 20px;border: 1px solid black;border-radius: 50%;display: flex;justify-content: center;align-items: center;">
							{{index + 1}}</div>
						<el-select style="width:70%;" v-model="item.id" @change="handlePointChange(item)"
							@visible-change="handlePointVisibleChange(item)" :key="index">
							<el-option v-for="items in areaList" filterable :key="items.id" :label="items.name"
								:value="items.id">
							</el-option>
						</el-select>
						<el-button @click.prevent="removeDomain(item)" v-if="PointList.length>0">删除</el-button>
					</div>
				</div>
				<el-button @click="addDomain" style="height: 40px;margin-left: 10px;">新增途径点</el-button>
			</div>




			<div id="map" class="map-wrapper"></div>



			<div slot="footer" class="dialog-footer" style="margin-top: 10px;text-align: center;">
				<el-button @click="dialogFormVisibleRw=false">取 消</el-button>
				<el-button type="primary" @click="addmissionNoticeTo()">确 定</el-button>
			</div>


		</el-dialog>

	</div>
</template>

<script>

	import 'quill/dist/quill.core.css'
	import 'quill/dist/quill.snow.css'
	import 'quill/dist/quill.bubble.css'
	import axios from 'axios';
	import {
		jsonp
	} from 'vue-jsonp'
	export default {
		data() {
			return {
				size: 10,
				page: 1,
				state: '',
				limit: 10,
				activeName: 'first',
				tableDataLoading: true,
				startPoint: '',
				endPoint: '',
				homeData: [],
				statesnum: [
					{
						value: 0,
						label: '快递柜'
					},
					{
						value: 1,
						label: '仓库'
					}
				],
				dialogFormVisible: false,
				// 添加/修改任务
				dialogFormVisibleRw: false,
				titles: '',
				map: null,
				MAP_KEY: 'NMEBZ-UPS3C-VBQ2B-ADNFP-LX6QH-NRBP5', // 腾讯地图API Key
				tableData: {
					"area": undefined,
					"areaCode": undefined,
					"endPointLat": undefined,
					"endPointLng": undefined,
					"id": undefined,
					"riderId": undefined,
					"riderName": undefined,
					"startPointLat": undefined,
					"startPointLng": undefined,
					"startPointName": undefined,
					"endPointName": undefined,
					"wayPoints": [
						// {
						//   "latitude": 0,
						//   "longitude": 0
						// }
					]
				},
				queryForm: {
					type: undefined
				},
				driverList: [],//司机列表
				areaList: [],//点位列表
				areaLists: [],//总点位列表
				startPoints: {},
				endPoints: {},
				PointList: [],//途径点列表
				zanPointList: '',//暂存途径点列表
			}
		},
		methods: {

			handleSizeChange1(val) {
				this.limit = val
				this.homeSelect()
			},
			handleCurrentChange1(val) {
				this.page = val
				this.homeSelect()
			},


			handleClick(tab, event) { },

			// 选择司机
			SelectDriver(row) {

				let data = this.driverList.find(item => item.userId == row);
				this.tableData.riderId = data.userId;
				this.tableData.riderName = data.userName;
			},

			//根据经纬度从this.areaLists中获取地址名称
			getAddressLatLng(lat, lng) {
				let data = this.areaLists.find(item => item.lat == lat && item.lng == lng);
				if (data) {
					return data.name;
				}
				return '';
			},

			//根据途径点每一项经纬度从this.areaLists中获取地址名称
			getWayPointsString(data) {
				if (data && data.length > 0) {
					return data.map(item => {
						let point = this.areaLists.find(it => it.lat == item.latitude && it.lng == item.longitude);
						return point ? point.name : '';
					}).join(', ');
				}
			},

			// 选择区域
			areaSeclect(row) {
				this.setRest()
				this.homeSelects()
			},
			// 选择发车点
			SelectStartPoint(row) {
				if (JSON.stringify(this.startPoints).length > 2 && this.areaList.indexOf(this.startPoints) == -1) {
					this.areaList.push(this.startPoints);
				}

				let data = this.areaList.find(item => item.id == row);
				this.startPointLng = data.lng;
				this.startPointLat = data.lat;
				this.filterAreaList(row);
				this.startPoints = data;


			},
			// 选择停车点
			SelectEndPoint(row) {

				if (JSON.stringify(this.endPoints).length > 2 && this.areaList.indexOf(this.endPoints) == -1) {
					this.areaList.push(this.endPoints);
				}
				let data = this.areaList.find(item => item.id == row);
				this.endPointLng = data.lng;
				this.endPointLat = data.lat;
				this.filterAreaList(row);
				this.endPoints = data;
			},
			//过滤点位列表
			filterAreaList(row) {
				var index = this.areaList.findIndex(item => item.id == row)
				if (index !== -1) {
					this.areaList.splice(index, 1)
				}
			},

			//打开途径点下拉框的事件
			handlePointVisibleChange(val) {
				this.zanPointList = val.id;
			},

			// 处理途径点选择变化
			handlePointChange(val) {
				if (this.zanPointList && this.zanPointList != val.id) {
					this.areaList.push(this.areaLists.find(it => it.id == this.zanPointList));
				}
				let data = this.areaList.find(item => item.id == val.id);
				this.filterAreaList(val.id);
			},


			removeDomain(item) {
				var index = this.PointList.indexOf(item)
				if (index !== -1) {
					if (item.id) {
						this.areaList.push(this.areaLists.find(it => it.id == item.id));
					}

					console.log(this.areaList);

					this.PointList.splice(index, 1)
					// 强制更新视图以确保下拉框正确显示
					this.$forceUpdate();
				}
			},


			addDomain() {
				this.PointList.push({
					id: undefined,
				});
			},

			// 删除
			compile(row) {
				this.$confirm(`确定删除当前点位?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$http({
						url: this.$http.adornUrl('point/delete'),
						method: 'post',
						data: this.$http.adornData([row.id])
					}).then(({
						data
					}) => {
						if (data.code == 0) {
							this.$message({
								message: '删除成功',
								type: 'success',
								duration: 1500,
								onClose: () => {
									this.homeSelect()
								}
							})
						} else {
							this.$notify({
								title: '提示',
								duration: 1800,
								message: data.msg,
								type: 'warning'
							})
						}

					})
				})
			},

			// 获取司机列表
			dataSelect() {
				this.tableDataLoading = true
				this.$http({
					url: this.$http.adornUrl('adminerrand/findAllUser'),
					method: 'get',
					params: this.$http.adornParams({
						'page': this.page,
						'limit': this.limit,
						'isDriver': 1
					})
				}).then(({
					data
				}) => {
					if (data.code == 0) {
						let returnData = data.data.list
						this.driverList = returnData
					}
				})
			},

			//分析类别名称
			seclectType(type) {
				if (type != undefined || type != null || type != '') {
					return this.statesnum.find(it => it.value == type).label
				} else {
					return ''
				}
			},

			setRest() {
				this.areaList = []
				this.startPoints = {}
				this.endPoint = {}
				this.endPoints = {}
				this.PointList = []//途径点列表
				this.zanPointList = ''//暂存途径点列表
				this.startPoint = ''
				this.endPoint = ''
			},

			// 查看
			looking(row) {
				this.titles = '查看路线'
				this.dialogFormVisibleRw = true
				this.tableData = row
				this.homeSelects()
				this.setRest()
				this.$nextTick(() => {
					this.initMap(row.lng, row.lat);
				})
			},

			// 获取数据列表
			homeSelect() {
				this.tableDataLoading = true
				this.$http({
					url: this.$http.adornUrl(`riderLine/list`),
					method: 'get',
					params: this.$http.adornParams({
						'page': this.page,
						'limit': this.limit,
						'type': this.queryForm.type
					})
				}).then(({
					data
				}) => {
					this.tableDataLoading = false
					if (data.code == 0) {
						this.homeData = data.page
					}
				})
			},

			// 获取数据列表
			homeSelects() {
				this.$http({
					url: this.$http.adornUrl(`point/list`),
					method: 'get',
					params: this.$http.adornParams({
						'page': this.page,
						'limit': 999,
						'area': this.tableData.area
					})
				}).then(({
					data
				}) => {
					if (data.code == 0) {

						this.areaList = [...data.page.list]
						this.$nextTick(() => {
							var arry = [...data.page.list]
							const tableData = this.tableData;
							arry.forEach(it => {

								if (tableData.startPointLat == it.lat && tableData.startPointLng == it.lng) {
									this.startPoint = it.id;
									this.SelectStartPoint(it.id)

								}
								if (tableData.endPointLat == it.lat && tableData.endPointLng == it.lng) {
									this.endPoint = it.id;
									this.SelectEndPoint(it.id)
								}
							});

							if (this.tableData.wayPoints && this.tableData.wayPoints.length > 0) {
								this.tableData.wayPoints.forEach(item => {
									let data = arry.find(it => {
										if (it.lat == item.latitude && it.lng == item.longitude) {
											return it;
										}
									});
									if (data) {
										this.PointList.push({
											id: data.id,
										});
										this.$nextTick(() => {
											// 使用handlePointChange方法而不是SelectEndPoint方法
											this.handlePointChange({ id: data.id });
										});
									}
								});
							} else {
								this.PointList = [];
							}
						});
					}
				})
			},
			// 获取数据列表
			homeSelects2() {
				this.$http({
					url: this.$http.adornUrl(`point/list`),
					method: 'get',
					params: this.$http.adornParams({
						'page': this.page,
						'limit': 9999,
					})
				}).then(({
					data
				}) => {
					if (data.code == 0) {
						this.areaLists = [...data.page.list];
					}
				})
			},



			// 重置
			cleans() {
				this.queryForm.type = undefined;
				this.page = 1;
				this.limit = 10;
				this.homeSelect()
			},

			// 添加/修改 任务
			addBtn() {
				this.titles = '添加路线'
				this.tableData = {
					"area": undefined,
					"endPointLat": undefined,
					"endPointLng": undefined,
					"id": undefined,
					"riderId": undefined,
					"riderName": undefined,
					"startPointLat": undefined,
					"startPointLng": undefined,
					"wayPoints": [],
					"startPointName": undefined,
					"endPointName": undefined,
				}
				this.setRest()
				this.dialogFormVisibleRw = true
				this.initMap();// 默认洛阳智能科技产业园
			},
			// 确定添加/修改
			addmissionNoticeTo() {

				if (!this.tableData.riderId) {
					this.$message.warning('请选择司机');
					return;
				}

				if (this.startPoint.length == 0) {
					this.$message.warning('请选择出发点');
					return;
				} else {
					let data = this.areaLists.find(it => it.id == this.startPoint)
					this.tableData.startPointLat = data.lat;
					this.tableData.startPointLng = data.lng;
					this.tableData.startPointName = data.name;
				}

				if (this.endPoint.length == 0) {
					this.$message.warning('请选择停车点');
					return;
				} else {
					let data = this.areaLists.find(it => it.id == this.endPoint)
					this.tableData.endPointLat = data.lat;
					this.tableData.endPointLng = data.lng;
					this.tableData.endPointName = data.name;
				}

				if (this.PointList.length > 0) {
					this.tableData.wayPoints = this.PointList.map((item, index) => {
						let data = this.areaLists.find(it => it.id == item.id);
						return {
							latitude: data.lat,
							longitude: data.lng,
							name: data.name,
							sort: index + 1
						}
					});
				} else {
					this.tableData.wayPoints = [];
				}

				if (this.tableData.id) {
					this.$http({
						url: this.$http.adornUrl(`riderLine/update`),
						method: 'post',
						data: this.$http.adornData(this.tableData)
					}).then(({ data }) => {
						if (data.code == 0) {
							this.$message.success('修改成功');
							this.dialogFormVisibleRw = false
						}else{
							this.$message.warning(data.msg);
						}
						this.homeSelect();
					
					})
				} else {
					this.$http({
						url: this.$http.adornUrl(`riderLine/save`),
						method: 'post',
						data: this.$http.adornData(this.tableData)
					}).then(({ data }) => {

						if (data.code == 0) {
							this.$message.success('添加成功');
							this.dialogFormVisibleRw = false
						}else{
							this.$message.error('添加失败');
						}
						this.homeSelect();
					})
				}
				
			},



			// 初始化地图
			initMap(lng, lat) {
				// 加载腾讯地图API
				const script = document.createElement('script');
				script.type = 'text/javascript';
				script.src = `https://map.qq.com/api/js?v=2.exp&key=${this.MAP_KEY}&callback=onMapCallback`;
				document.head.appendChild(script);

				window.onMapCallback = () => {
					// 确定地图中心点
					let centerLat = lat || 34.672857153159846;
					let centerLng = lng || 112.43718266487122;
					// 初始化地图
					this.map = new qq.maps.Map(document.getElementById('map'), {
						center: new qq.maps.LatLng(centerLat, centerLng),
						zoom: 12,
						mapTypeId: qq.maps.MapTypeId.ROADMAP
					});

					// 如果提供了坐标，则添加标记
					if (lng && lat) {
						const marker = new qq.maps.Marker({
							position: new qq.maps.LatLng(centerLat, centerLng),
							map: this.map
						});
						this.currentMarker = marker;
					}

					// 添加点击事件监听器（仅在添加/编辑模式下）
					if (!lat || !lng) {
						qq.maps.event.addListener(this.map, 'click', (event) => {
							// 清除之前的标记
							if (this.currentMarker) {
								this.currentMarker.setMap(null);
							}

							// 创建新标记
							this.currentMarker = new qq.maps.Marker({
								position: event.latLng,
								map: this.map
							});

							// 获取地址信息
							this.getAddressByLatLng(event.latLng);
						});
					}
				};
			},


			// 根据经纬度获取地址信息
			getAddressByLatLng(latLng) {
				let data = `${latLng.lat},${latLng.lng}`;
				jsonp(`https://apis.map.qq.com/ws/geocoder/v1/?location=${data}&key=${this.MAP_KEY}&output=jsonp`, {
					myCustomUrlParam: 'veryNice'
				}).then(res => {
					if (res.status === 0) {
						const address_component = res.result.address_component;
						// this.tableData.lat = res.result.location.lat;
						// this.tableData.lng = res.result.location.lng;
						this.tableData.area = address_component.province + address_component.city + address_component.district;
						this.tableData.areaCode = res.result.ad_info.adcode;
						this.startPoint = ''
						this.endPoint = '';
						this.areaSeclect()
						// this.tableData.name = res.result.formatted_addresses.recommend
					} else {
						this.$message.error('未找到该地址，请重新输入');
					}
				}).catch(error => {
					console.log('error', error)
				});
			},


		},
		mounted() {
			this.homeSelect()
			this.dataSelect();
			this.homeSelects2();
		}
	}
</script>

<style scoped>
	.customWidth {
		width: 80% !important;
	}



	.cards {
		padding: 0 8px;
		margin-bottom: 15px;
	}



	.bannerbtn {
		display: flex;
		border-top: none !important;
		border: 1px solid #e8e8e8;
		padding: 11px;
		font-size: 14px;
		color: #3E8EF7;
	}

	.bannerbtn a {
		flex: 1;
		text-align: center;
		color: #3E8EF7 !important;
		text-decoration: none;
	}

	.imgs {
		position: relative;
		border-radius: 6px;
		width: 148px;
		height: 148px;
		margin-right: 10px;
		display: inline-block;
	}

	.dels {
		position: absolute;
		top: 0;
		left: 0;
		display: none;
	}

	.dels .el-icon-delete {
		line-height: 148px;
		padding-left: 58px;
		font-size: 25px;
		color: #fff;
	}

	.imgs:hover .dels {
		width: 100%;
		height: 100%;
		background: #000;
		display: block;
		opacity: 0.5;
	}

	.bqList {
		padding: 4px 14px;
		margin: 4px;
		border: 1px solid #efefef;
		font-size: 12px;
		color: #999;
		border-radius: 4px;
		margin-right: 15px;
	}

	.delss {
		display: none;
		position: relative;
	}

	.delss .el-icon-delete {
		position: absolute;
		top: 0;
	}

	.bqList:hover .delss {
		display: initial;
		opacity: 0.5;

	}

	.map-wrapper {
		width: 70%;
		height: 200px;
		margin-left: 100px;
	}
</style>